{extend name="layout/base" /}

{block name="css"}
<style>
/* 统计卡片样式 */
.management-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 32px;
}

.stat-card {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.2);
    position: relative;
    overflow: hidden;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    backdrop-filter: blur(10px);
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--primary-color), #667eea, #764ba2);
    border-radius: 16px 16px 0 0;
}

.stat-card:hover {
    transform: translateY(-8px) scale(1.02);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    border-color: rgba(102, 126, 234, 0.3);
}

.stat-card:nth-child(1)::before {
    background: linear-gradient(90deg, #667eea, #764ba2);
}

.stat-card:nth-child(2)::before {
    background: linear-gradient(90deg, #f093fb, #f5576c);
}

.stat-card:nth-child(3)::before {
    background: linear-gradient(90deg, #4facfe, #00f2fe);
}

.stat-card:nth-child(4)::before {
    background: linear-gradient(90deg, #43e97b, #38f9d7);
}

.stat-icon {
    font-size: 32px;
    display: block;
    margin-bottom: 12px;
    filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.stat-number {
    font-size: 28px;
    font-weight: 700;
    color: #2c3e50;
    display: block;
    margin-bottom: 4px;
    background: linear-gradient(135deg, #2c3e50, #3498db);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.stat-label {
    font-size: 14px;
    color: #6c757d;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    display: block;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .management-stats {
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 16px;
        margin-bottom: 24px;
    }
    
    .stat-card {
        padding: 20px;
    }
    
    .stat-icon {
        font-size: 28px;
    }
    
    .stat-number {
        font-size: 24px;
    }
    
    .stat-label {
        font-size: 13px;
    }
}

@media (max-width: 480px) {
    .management-stats {
        grid-template-columns: 1fr 1fr;
        gap: 12px;
    }
    
    .stat-card {
        padding: 16px;
        text-align: center;
    }
    
    .stat-icon {
        font-size: 24px;
        margin-bottom: 8px;
    }
    
    .stat-number {
        font-size: 20px;
    }
    
    .stat-label {
        font-size: 12px;
    }
}

/* 岗位管理特定样式 */
.filter-section {
    background: white;
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #f1f3f4;
}

.filter-title {
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-controls {
    display: flex;
    gap: 20px;
    align-items: end;
    flex-wrap: wrap;
}

.filter-group {
    flex: 1;
    min-width: 200px;
}

.department-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 12px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.position-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #f1f3f4;
    transition: all 0.3s ease;
}

.position-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.position-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
}

.position-name {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
    margin: 0;
}

.position-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 16px;
}

.position-department {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #6c757d;
    font-size: 14px;
}

.position-time {
    color: #adb5bd;
    font-size: 13px;
}



.position-actions {
    display: flex;
    gap: 8px;
    justify-content: flex-end;
}

.grid-view {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
}

.list-view .position-card {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 16px 20px;
}

.list-view .position-header {
    flex: 1;
    margin-bottom: 0;
}

.list-view .position-meta {
    flex-direction: row;
    margin-bottom: 0;
}



.view-toggle {
    display: flex;
    gap: 8px;
    margin-left: auto;
}

.view-btn {
    padding: 8px 12px;
    border: 1px solid #dee2e6;
    background: white;
    color: #6c757d;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.view-btn.active {
    background: #667eea;
    color: white;
    border-color: #667eea;
}

.view-btn:hover:not(.active) {
    background: #f8f9fa;
    border-color: #adb5bd;
}

@media (max-width: 768px) {
    .filter-controls {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-group {
        min-width: auto;
    }
    
    .grid-view {
        grid-template-columns: 1fr;
    }
    
    .position-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }
    
    .position-actions {
        justify-content: flex-start;
    }
    
    .view-toggle {
        margin-left: 0;
        margin-top: 16px;
    }
}
</style>
{/block}

{block name="content"}
<div class="page-container">
    <div class="page-header">
        <h1 class="page-title">
            <span>💼</span>
            岗位管理
        </h1>
        <p class="page-subtitle">管理各部门岗位信息，为名片生成提供职位选择</p>
    </div>
    
    <!-- 统计卡片 -->
    <div class="management-stats">
        <div class="stat-card">
            <span class="stat-icon">💼</span>
            <span class="stat-number" id="totalPositions">0</span>
            <span class="stat-label">总岗位数</span>
        </div>
        <div class="stat-card">
            <span class="stat-icon">🏢</span>
            <span class="stat-number" id="totalDepartments">0</span>
            <span class="stat-label">涉及部门</span>
        </div>
        <div class="stat-card">
            <span class="stat-icon">📈</span>
            <span class="stat-number" id="recentlyAdded">0</span>
            <span class="stat-label">本月新增</span>
        </div>
        <div class="stat-card">
            <span class="stat-icon">⚡</span>
            <span class="stat-number">实时</span>
            <span class="stat-label">数据同步</span>
        </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
        <div class="filter-title">
            <span>🔍</span>
            筛选条件
        </div>
        <div class="filter-controls">
            <div class="filter-group">
                <label class="form-label" for="departmentFilter">按部门筛选</label>
                <select id="departmentFilter" class="form-control form-select">
                    <option value="">全部部门</option>
                </select>
            </div>
            <div class="filter-group">
                <label class="form-label" for="searchInput">搜索岗位</label>
                <input type="text" id="searchInput" class="form-control" placeholder="输入岗位名称搜索...">
            </div>
            <div class="filter-group">
                <button id="clearFilter" class="btn btn-outline">
                    <span>🔄</span>
                    清除筛选
                </button>
            </div>
        </div>
    </div>
    
    <!-- 操作区域 -->
    <div class="management-header">
        <div class="action-buttons">
            <button id="addBtn" class="btn btn-primary btn-icon">
                <span>➕</span>
                添加岗位
            </button>
            <button id="refreshBtn" class="btn btn-outline btn-icon">
                <span>🔄</span>
                刷新数据
            </button>
        </div>
        
        <div class="view-toggle">
            <button class="view-btn active" data-view="grid" title="网格视图">
                <span>⊞</span>
            </button>
            <button class="view-btn" data-view="list" title="列表视图">
                <span>☰</span>
            </button>
        </div>
    </div>
    
    <!-- 岗位列表 -->
    <div id="positionContainer" class="grid-view">
        <!-- 通过JavaScript动态加载 -->
    </div>
    
    <!-- 空状态 -->
    <div id="emptyState" class="empty-state hidden">
        <div class="empty-icon">💼</div>
        <div class="empty-message">暂无岗位数据</div>
        <button class="btn btn-primary" onclick="$('#addBtn').click()">
            <span>➕</span>
            添加第一个岗位
        </button>
    </div>
</div>

<!-- 岗位编辑模态框 -->
<div id="positionModal" class="modal hidden">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle" class="modal-title">添加岗位</h2>
            <button id="closeModal" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
            <form id="positionForm">
                <input type="hidden" id="positionId">
                
                <div class="form-section">
                    <div class="form-section-title">
                        <span>📝</span>
                        基本信息
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="positionName">岗位名称 <span class="required">*</span></label>
                        <input type="text" id="positionName" name="name" class="form-control" placeholder="请输入岗位名称" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="departmentId">所属部门 <span class="required">*</span></label>
                        <select id="departmentId" name="department_id" class="form-control form-select" required>
                            <option value="">请选择部门</option>
                        </select>
                    </div>
                    

                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button id="cancelBtn" class="btn btn-outline">取消</button>
            <button id="saveBtn" class="btn btn-primary">
                <span>💾</span>
                保存
            </button>
        </div>
    </div>
</div>
{/block}

{block name="js"}
<script>
$(document).ready(function() {
    let allPositions = [];
    let allDepartments = [];
    let currentView = 'grid';
    
    // 初始化
    loadDepartments();
    loadPositionList();
    
    // 事件绑定
    $('#addBtn').click(() => openAddModal());
    $('#refreshBtn').click(() => loadPositionList());
    $('#closeModal, #cancelBtn').click(() => closeModal());
    $('#saveBtn').click(() => savePosition());
    $('#departmentFilter').change(() => filterPositions());
    $('#searchInput').on('input', debounce(filterPositions, 300));
    $('#clearFilter').click(() => clearFilters());
    
    // 视图切换
    $('.view-btn').click(function() {
        const view = $(this).data('view');
        switchView(view);
    });
    
    // 模态框事件
    $(window).click(function(event) {
        if (event.target == $('#positionModal')[0]) {
            closeModal();
        }
    });
    
    $(document).keydown(function(event) {
        if (event.keyCode === 27) {
            closeModal();
        }
    });
    
    // 加载部门列表
    function loadDepartments() {
        $.ajax({
            url: '/department/getList',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {
                    allDepartments = res.data;
                    let options = '<option value="">全部部门</option>';
                    let modalOptions = '<option value="">请选择部门</option>';
                    
                    allDepartments.forEach(function(dept) {
                        options += `<option value="${dept.id}">${dept.name}</option>`;
                        modalOptions += `<option value="${dept.id}">${dept.name}</option>`;
                    });
                    
                    $('#departmentFilter').html(options);
                    $('#departmentId').html(modalOptions);
                }
            }
        });
    }
    
    // 加载岗位列表
    function loadPositionList() {
        const refreshBtn = document.getElementById('refreshBtn');
        setLoading(refreshBtn, true);
        
        $.ajax({
            url: '/position/getList',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {
                    allPositions = res.data;
                    updateStats();
                    renderPositions(allPositions);
                } else {
                    showMessage('加载岗位列表失败: ' + res.msg, 'error');
                }
            },
            error: function() {
                showMessage('加载岗位列表失败', 'error');
            },
            complete: function() {
                setLoading(refreshBtn, false);
            }
        });
    }
    
    // 更新统计
    function updateStats() {
        $('#totalPositions').text(allPositions.length);
        
        // 直接从部门接口获取准确的部门总数
        $.ajax({
            url: '/department/getList',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {
                    $('#totalDepartments').text(res.data.length);
                } else {
                    $('#totalDepartments').text('-');
                }
            },
            error: function() {
                $('#totalDepartments').text('-');
            }
        });
        
        const thisMonth = new Date().getMonth() + 1;
        const recentlyAdded = allPositions.filter(pos => {
            const createMonth = new Date(pos.create_time).getMonth() + 1;
            return createMonth === thisMonth;
        }).length;
        $('#recentlyAdded').text(recentlyAdded);
    }
    
    // 渲染岗位列表
    function renderPositions(positions) {
        if (positions.length === 0) {
            $('#positionContainer').empty();
            $('#emptyState').removeClass('hidden');
            return;
        }
        
        $('#emptyState').addClass('hidden');
        
        let html = '';
        positions.forEach(function(pos) {
            // 通过department_id查找部门名称
            const department = allDepartments.find(dept => dept.id == pos.department_id);
            const departmentName = department ? department.name : '未分配部门';
            const createTime = formatDate(pos.create_time);
            
            if (currentView === 'grid') {
                html += `
                    <div class="position-card">
                        <div class="position-header">
                            <h3 class="position-name">${pos.name}</h3>
                            <div class="position-actions">
                                <button class="btn btn-sm btn-warning btn-edit" data-id="${pos.id}" title="编辑">
                                    <span>✏️</span>
                                </button>
                                <button class="btn btn-sm btn-danger btn-delete" data-id="${pos.id}" title="删除">
                                    <span>🗑️</span>
                                </button>
                            </div>
                        </div>
                        <div class="position-meta">
                            <div class="position-department">
                                <span class="department-badge">
                                    <span>🏢</span>
                                    ${departmentName}
                                </span>
                            </div>
                            <div class="position-time">${createTime}</div>
                        </div>
                    </div>
                `;
            } else {
                html += `
                    <div class="position-card">
                        <div class="position-header">
                            <div>
                                <h3 class="position-name">${pos.name}</h3>
                                <div class="position-meta">
                                    <span class="department-badge">
                                        <span>🏢</span>
                                        ${departmentName}
                                    </span>
                                    <span class="position-time">${createTime}</span>
                                </div>
                            </div>
                        </div>
                        <div class="position-actions">
                            <button class="btn btn-sm btn-warning btn-edit" data-id="${pos.id}" title="编辑">
                                <span>✏️</span>
                            </button>
                            <button class="btn btn-sm btn-danger btn-delete" data-id="${pos.id}" title="删除">
                                <span>🗑️</span>
                            </button>
                        </div>
                    </div>
                `;
            }
        });
        
        $('#positionContainer').html(html);
        bindTableEvents();
    }
    
    // 切换视图
    function switchView(view) {
        currentView = view;
        $('.view-btn').removeClass('active');
        $(`.view-btn[data-view="${view}"]`).addClass('active');
        
        const container = $('#positionContainer');
        container.removeClass('grid-view list-view').addClass(`${view}-view`);
        
        renderPositions(getFilteredPositions());
    }
    
    // 筛选岗位
    function filterPositions() {
        const filtered = getFilteredPositions();
        renderPositions(filtered);
    }
    
    // 获取筛选后的岗位
    function getFilteredPositions() {
        const departmentId = $('#departmentFilter').val();
        const searchText = $('#searchInput').val().toLowerCase().trim();
        
        return allPositions.filter(pos => {
            const matchDepartment = !departmentId || pos.department_id == departmentId;
            const matchSearch = !searchText || pos.name.toLowerCase().includes(searchText);
            return matchDepartment && matchSearch;
        });
    }
    
    // 清除筛选
    function clearFilters() {
        $('#departmentFilter').val('');
        $('#searchInput').val('');
        renderPositions(allPositions);
    }
    
    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }
    
    // 防抖函数
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
    // 绑定事件
    function bindTableEvents() {
        $('.btn-edit').click(function() {
            const id = $(this).data('id');
            openEditModal(id);
        });
        
        $('.btn-delete').click(function() {
            const id = $(this).data('id');
            const position = allPositions.find(p => p.id == id);
            if (confirm(`确定要删除岗位"${position.name}"吗？\n\n注意：删除岗位可能会影响相关的名片数据。`)) {
                deletePosition(id);
            }
        });
    }
    
    // 模态框操作
    function openAddModal() {
        $('#modalTitle').text('添加岗位');
        $('#positionId').val('');
        $('#positionForm')[0].reset();
        $('#positionModal').removeClass('hidden').show();
        setTimeout(() => $('#positionName').focus(), 300);
    }
    
    function openEditModal(id) {
        const pos = allPositions.find(item => item.id == id);
        if (pos) {
            $('#modalTitle').text('编辑岗位');
            $('#positionId').val(pos.id);
            $('#positionName').val(pos.name);
            $('#departmentId').val(pos.department_id);

            $('#positionModal').removeClass('hidden').show();
            setTimeout(() => $('#positionName').focus(), 300);
        } else {
            showMessage('岗位不存在', 'error');
        }
    }
    
    function closeModal() {
        $('#positionModal').addClass('hidden').hide();
    }
    
    // 保存岗位
    function savePosition() {
        const id = $('#positionId').val();
        const name = $('#positionName').val().trim();
        const departmentId = $('#departmentId').val();
        
        console.log('保存岗位数据:', { id, name, departmentId });
        console.log('部门选择框的值:', $('#departmentId').val());
        console.log('部门选择框的HTML:', $('#departmentId').html());
        
        if (!name) {
            showMessage('岗位名称不能为空', 'error');
            $('#positionName').focus();
            return;
        }
        if (!departmentId || departmentId === '' || departmentId === null) {
            console.log('部门验证失败，当前值:', departmentId);
            showMessage('请选择所属部门', 'error');
            $('#departmentId').focus();
            return;
        }
        
        const saveBtn = document.getElementById('saveBtn');
        setLoading(saveBtn, true);
        
        const data = { name, department_id: departmentId };
        const url = id ? `/position/update/${id}` : '/position/add';
        
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {
                    closeModal();
                    loadPositionList();
                } else {
                    showMessage((id ? '更新失败: ' : '添加失败: ') + res.msg, 'error');
                }
            },
            error: function() {
                showMessage(id ? '更新失败' : '添加失败', 'error');
            },
            complete: function() {
                setLoading(saveBtn, false);
            }
        });
    }
    
    // 删除岗位
    function deletePosition(id) {
        $.ajax({
            url: `/position/delete/${id}`,
            type: 'POST',
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {
                    loadPositionList();
                } else {
                    showMessage('删除失败: ' + res.msg, 'error');
                }
            },
            error: function() {
                showMessage('删除失败', 'error');
            }
        });
    }
});
</script>
{/block}